package com.symbio.ishenapi.background.controller;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.symbio.ishenapi.background.model.*;
import com.symbio.ishenapi.common.bean.LoginUser;
import com.symbio.ishenapi.common.bean.QueryModel;
import com.symbio.ishenapi.common.controller.BaseController;
import io.jboot.web.controller.annotation.RequestMapping;

import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RequestMapping("/tmDoctorUserController")
public class TmDoctorUserController extends BaseController {

    /**
     * 列表分页条件查询
     */
    public void findList(){
        QueryModel queryModel = getQueryModel();
        String queryNP = getPara("queryNP");
        LoginUser loginUser = getLoginUser();
        String Ids = loginUser.getDoctorIds();
        if (Ids.endsWith(",")) {
            Ids = Ids.substring(0,(Ids.length() - 1));
        }
        Map map = TmDoctorUser.dao.findList(queryModel,queryNP,Ids);
        renderPageJsonRet(map.get("count"),map.get("data"));
    }

    /**
     * 医生单条新增
     */
    public void save(){
        TmDoctorUser doctorUser = (TmDoctorUser)getReqBodyObject(TmDoctorUser.class);
        TmDoctorUser userPhne = TmDoctorUser.dao.findByPhone(doctorUser.getUserMobilePhone());
        if(userPhne!=null){
            renderJsonError(50002,"手机号已添加");
            return;
        }
        doctorUser.setCreateTtime(new Date());
        //添加里 服务默认关闭
        doctorUser.setServerStatus("0");
        if (doctorUser.save()){
            TmDoctorUser user = TmDoctorUser.dao.findByPhone(doctorUser.getUserMobilePhone());
            Map map = new HashMap();
            map.put("doctorId",user.getId());
            map.put("doctorName",user.getUserName());
            map.put("departmentId",user.getDepartmentId());
            map.put("memberRoleCode",user.getPostType());
            renderJsonRet(map);
        }
        else {
            renderJsonError(50002,"医生添加");
        }
    }

    /**
     * chen
     * 医生列表单条修改
     */
    public void update(){
        try {
            TmDoctorUser user = (TmDoctorUser)getReqBodyObject(TmDoctorUser.class);
            user.update();
            Map map = new HashMap();
            map.put("doctorId",user.getId());
            map.put("doctorName",user.getUserName());
            map.put("departmentId",user.getDepartmentId());
            map.put("memberRoleCode",user.getPostType());
            renderJsonRet(map);
        }catch (Exception e){
            renderJsonError(40005);
        }

    }

    /**
     * 修改回显
     */
    public void findDoctorUserById(){
        int id = getParaToInt("id");
        TmDoctorUser tmDoctorUser = TmDoctorUser.dao.findDoctorUserPostById(id);
        if(tmDoctorUser != null){
            renderJson(tmDoctorUser);
        }else {
            renderJsonError(40005,"用户信息为空");
        }
    }

    /**
     * wy:查询医网签
     */
    public void findByIdToSignature(){
        int id = getParaToInt("id");
        TmDoctorUser tmDoctorUser = TmDoctorUser.dao.findDoctorUserPostById(id);
        if(tmDoctorUser.getSignatureImg() != null && !"".equals(tmDoctorUser.getSignatureImg())){
            renderJsonRet(tmDoctorUser.getSignatureImg());
        }else {
            renderJsonRet(tmDoctorUser.getUserName());
        }
    }

    /**
     * 医生列表单条删除
     */
    public void delete(){
        int id = getParaToInt("id");
        if(TmDoctorUser.dao.deleteDtUser(id) > 0){
            renderJsonRet(40004);
        }else {
            renderJsonError(40005);
        }
    }

    /**
     * 医生模块禁功能
     */
    public void setStates(){
        int status = getParaToInt("status");
        String ids = getPara("ids");
        if(TmDoctorUser.dao.setStates(ids,status) > 0){
            renderJsonRet(40004);
        }else {
            renderJsonError(40005);
        }
    }

    /**
     * 添加成员时获取的医生列表
     */
    public  void findDoctorList(){
        String did = getPara("id");
        String userMobilePhone = getPara("userMobilePhone");
        List<TmDoctorInsuranceCorps> tmDoctorInsuranceCorpsList = TmDoctorInsuranceCorps.dao.findList(did);
        String id = "";
        if(tmDoctorInsuranceCorpsList != null || tmDoctorInsuranceCorpsList.size() > 0){
            for(int i = 0;i < tmDoctorInsuranceCorpsList.size();i++){
                if(!"".equals(id)){

                    id += ","+tmDoctorInsuranceCorpsList.get(i).getStr("doctorId");
                }else{
                    id = tmDoctorInsuranceCorpsList.get(i).getStr("doctorId");
                }
            }
        }
        Map map = TmDoctorUser.dao.findDoctorByUserMobilePhone(id,userMobilePhone,getQueryModel());
        renderPageJsonRet(map.get("count"),map.get("data"));
    }

    /**
     * 科室页面-根据医生ID查询医生的科室名称
     * Param doctorId 医生ID
     */
    public void findDoctorDemById(){
        try {
            String doctorId = getPara("doctorId");
            renderJson(TmDoctorUser.dao.findDoctorDemById(doctorId));
        }catch (Exception e){
            renderJsonError(50002,"查询医生医院科室");
        }
    }

    /**
     * chen
     * 分组成员关联医生的患者列表查询
     */
    public void findGroupMemberList(){
        try {
            String hosId = getPara("hosId");
            Map map = TmDoctorUser.dao.findGroupMemberList(getQueryModel(),hosId);
            renderPageJsonRet(map.get("count"),map.get("data"));
        }catch (Exception e){
            renderJsonError(50002,"分组成员列表查询");
        }
    }

    /**
     * wy:根据医生ID的查询患者列表
     */
    public void findDoctorIdAndPatient() {
        String doctorId = getPara("doctorId");
        if (doctorId != null && !"".equals(doctorId.trim())){
            Map map = TmPatientDoctor.dao.findDoctorIdAndPatient(getQueryModel(),doctorId);
            renderPageJsonRet(map.get("count"),map.get("data"));
            renderJsonRet(map);
        }else {
            renderJsonError(400003,"关联患者");
        }
    }


    /**
     * wy:根据医生Id和患者来源
     *      查询患者列表
     */
    public void findIdAndUserSource() {
        String doctorId = getPara("doctorId");
        String userSource = getPara("userSource");
        if (doctorId != null && !"".equals(doctorId.trim())){
            Map map = TmPatientDoctor.dao.findIdAndUserSource(getQueryModel(),doctorId,userSource);
            renderPageJsonRet(map.get("count"),map.get("data"));
            renderJsonRet(map);
        }else {
            renderJsonError(400003,"关联患者");
        }
    }


    /**
     * 手机号模糊查询
     */
   /* public  void findDoctorByUserMobilePhone(){
        String  mid = getPara("id");
        BigInteger insuranceCorpsId = new BigInteger(mid);
        String userMobilePhone = getPara("UserMobilePhone");
        //这里baseTmDoctorUser.getId()是临时存放的保险团id
        List<Record> TmDoctorInsuranceCorpsList = tmDoctorInsuranceCorps.findDoctorInsuranceCorpsByInsuranceCorpsId(insuranceCorpsId);
        String id = "";
        if(TmDoctorInsuranceCorpsList != null || TmDoctorInsuranceCorpsList.size() > 0){
            for(int i = 0;i < TmDoctorInsuranceCorpsList.size();i++){
                if(!id.equals("")){

                    id += ","+TmDoctorInsuranceCorpsList.get(i).getStr("id");
                }else{
                    id = TmDoctorInsuranceCorpsList.get(i).getStr("id");
                }
            }
        }
        Map map = TmDoctorUser.dao.findDoctorByUserMobilePhone(id,userMobilePhone,getQueryModel());
        renderPageJsonRet(map.get("count"),map.get("data"));
    }*/

    /**
     * @Author jianghy
     * @Description 医生数据明细根据id回显基本信息
     * @date
     * @return void
     */
    public void queryBasisInfo() throws ParseException {
        Map<String,Object> map = new HashMap<>();
        int doctorId = getParaToInt("doctorId");
        TmDoctorUser tdu = TmDoctorUser.dao.findDoctorUserById(doctorId);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");//24小时制
        Date d1 = df.parse(df.format(new Date()));//现在时间
        Date d2 = df.parse(df.format(tdu.getCreateTtime()));
        long diff = d1.getTime() - d2.getTime();//这样得到的差值是毫秒级别
        long days = diff / (1000 * 60 * 60 * 24);
        long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60);
        long minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);
        map.put("inTime",""+days+"天"+hours+"小时"+minutes+"分");//入驻时间
        map.put("userName",tdu.getUserName());//医生姓名
        map.put("hostptial",tdu.getHostptial());//所属医院
        map.put("jobTitle",tdu.getJobTitle());//职称
        map.put("address",tdu.getAddress());//所在省
        map.put("createTime",tdu.getCreateTtime());//医生入驻时间
        map.put("dockingPeople",tdu.getDockingPeople());//医生对接人 暂定为空
        renderJsonRet(map);
    }
    /**
     * @Author jianghy
     * @Description 根据医生姓名、手机号、统计时段条件查询医生基础信息、以及运营-医生列表初始化信息查询
     * @date
     * @return void
     */
    public void initQueryDoctorListInfo(){
        int roleId = TmRoleInfo.dao.queryDoctorRoleId();//查询医生的角色id
        List<TmUserRole>  turList =  TmUserRole.dao.getUserIdByRoleId(roleId);//根据医生的角色id查看用户的id
        StringBuilder sb = new StringBuilder("");//拼接医生id
        for(int i=0;i<turList.size();i++){
            if(i == turList.size()-1){
                sb.append(turList.get(i).getUserId());
            }else{
                sb.append(turList.get(i).getUserId()+",");
            }
        }
        String userIds = sb.toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = sdf.format(new Date());
        String doctorName = getPara("doctorName");
        String phoneNumber = getPara("phoneNumber");
        String createStartTime = getPara("createStartTime");
        String createEndTime = getPara("createEndTime");
        if(doctorName==null||"".equals(doctorName)||"null".equals(doctorName)){
            doctorName = "";
        }
        if(phoneNumber==null||"".equals(phoneNumber)||"null".equals(phoneNumber)){
            phoneNumber = "";
        }
        if(createStartTime==null||"".equals(createStartTime)||"null".equals(createStartTime)){
            createStartTime = "1991-10-01";
        }
        if(createEndTime==null||"".equals(createEndTime)||"null".equals(createEndTime)){
            createEndTime = nowDate;
        }
        Map map = TmDoctorUser.dao.initQueryDoctorListInfo(userIds,doctorName,phoneNumber,createStartTime,createEndTime,getQueryModel());
        renderPageJsonRet(map.get("count"),map.get("data"));
    }

    /**获取未开启服务的医生id集合
     * author:chen
     *serverStatus  0.未开启 1.开启
     */
    public void findNoServiceDoctors(){
        //获取未设置服务的医生ID集合
        int serverStatus = getParaToInt("serverStatus");
        String sqlIds = "SELECT id FROM tm_doctor_user WHERE STATUS = 1 and userType = 0 and serverStatus = "+serverStatus+"";
        try {
            List<BigInteger> ids = Db.query(sqlIds);
            renderJsonRet(ids);
        }catch (Exception e){
            renderJsonError(50002,"获取没有服务的医生id集合");
        }
    }

    /**修改服务时调用方法  更改状态
     *  author:chen
     *  id:用户id
     */
    public void setUserServerStatus(){
        try {
            String id = getPara("id");
            TmDoctorUser.dao.setUserServerStatus(id);
            renderJsonError(50001,"修改用户服务状态");
        }catch (Exception e){
            renderJsonError(50002,"修改用户服务状态");
        }
    }

    /*****************************************************************************************************************************************************
     * 从doctor服务端迁移过来的方法
     */

    //迁移---根据Id查询医生信息
    public void findDoctorUser(){       //显示医生信息
        BigInteger id = new BigInteger(getPara("id"), 10);
        TmDoctorUser item = TmDoctorUser.dao.findById(id);
        if (item == null ) {
            renderJsonError(40003);
            return;
        }
        renderJsonRet(item);
    }

    //迁移---添加医生个人信息
    public void saveDoctorUser(){       //添加医生的个人信息
        TmDoctorUser user = (TmDoctorUser) getReqBodyObject(TmDoctorUser.class);
        user.setCreateTtime(new Date());
        if (user.getUserName() == null || "".equals(user.getUserName())) {
            renderJsonError(40003, "姓名");
        }else if (user.getUserMobilePhone() == null || "".equals(user.getUserMobilePhone())){
            renderJsonError(40003, "电话");
        }else if (user.getUserSex() == null || "".equals(user.getUserSex())){
            renderJsonError(40003, "性别");
        }else if (user.getUserCity() == null || "".equals(user.getUserCity())){
            renderJsonError(40003, "所在城市");
        }else if (user.getUserBirthday() == null || "".equals(user.getUserBirthday())){
            renderJsonError(40003, "出生日期");
        }
        else {
            user.save();
            renderJsonRet(40001);
        }
    }

    //迁移---修改医生信息
    public void updTmDoctorUser(){         //修改医生信息
        TmDoctorUser user = (TmDoctorUser) getReqBodyObject(TmDoctorUser.class);
        TmDoctorUser u = TmDoctorUser.dao.findById(user.getId());
        if (u != null) {
            if (!StrKit.isBlank(user.getUserName())){
                u.setUserName(user.getUserName());
            }
            if (!StrKit.isBlank(user.getUserEmail())) {
                u.setUserEmail(user.getUserEmail());
            }
            if (!StrKit.isBlank(user.getUserNickName())) {
                u.setUserNickName(user.getUserNickName());
            }
            if (!StrKit.isBlank(user.getUserSex())) {
                u.setUserSex(user.getUserSex());
            }
            if (!StrKit.isBlank(user.getUserCity())) {
                u.setUserCity(user.getUserCity());
            }
            if (!StrKit.isBlank(user.getUserIdCard())) {
                u.setUserIdCard(user.getUserIdCard());
            }
            if (user.getUserBirthday() != null) {
                u.setUserBirthday(user.getUserBirthday());////生日保存有问题 待修改
            }
            if (!StrKit.isBlank(user.getUserDetailedAddress())) {
                u.setUserDetailedAddress(user.getUserDetailedAddress());
            }
            if (!StrKit.isBlank(user.getUserPostCode())) {
                u.setUserPostCode(user.getUserPostCode());
            }
            if (!StrKit.isBlank(user.getUserHeadPortrait())) {
                u.setUserHeadPortrait(user.getUserHeadPortrait());
            }
            if (u.update()) {
                renderJsonRet(user.getId());
            } else {
                renderJsonError(40005);
            }
        }else{
            System.out.println("数据库中用户信息为空");
            renderJsonError(40003);
            return;
        }
    }

    //迁移---我的工作室
    /*
     * 我的工作室
     * */
    public void findWork(){ //查询医生信息
        TmDoctorUser user = (TmDoctorUser) getReqBodyObject(TmDoctorUser.class);
        renderJsonRet(TmDoctorUser.dao.selectDoctor(user.getId()));
    }

    //迁移---根据doctorType角色 查询医生id
    /**
     * @Author GuoShunYou
     * @Description 根据doctorType角色 查询医生id
     * @date 上午 10:30   2018/11/2
     * @return void
     */
    public void getdoctorId(){
        TmDoctorUser user = (TmDoctorUser) getReqBodyObject(TmDoctorUser.class);
        List<TmDoctorUser> list=TmDoctorUser.dao.getdoctorId(user.getDoctorType());
        if(list.size()<=0){
            renderJsonError(40003,"该角色对应医生");
            return;
        }else{
            String str=list.get(0).getId().toString();
            for(int i=1;i<list.size();i++){
                str+= ","+list.get(i).getId().toString();
            }
            renderJsonRet(str);
        }
    }

    //迁移---根据多个医生ID 查询对应的信息
    ////根据多个医生ID 查询对应的信息
    public void serchDoctorByMoreId(){
        String doctorId = getPara("doctorId");
        System.out.println("获取的医生列表ID为"+doctorId);
        renderJsonRet(TmDoctorUser.dao.findTmPatientDoctorList(doctorId));
    }

    /**
     *
     *
     * @Author GuoShunYou
     * @Description 获取保险团医生id
     * @date 下午 8:12   2018/11/12
     * @return void
     */
    public void getDoctorCorpId(){
       BigInteger id= TmDoctorUser.dao.doctorId();
       renderJsonRet(id);
    }
    /**
     * @Author jianghy
     * @Description 平台数据医生维度复购患者数柱状图初始化返回页面全部医生id
     * @date
     * @return void
     */
    public void queryDoctorAllInfo(){
        String roleName = getPara("roleName");
        renderJsonRet(TmDoctorUser.dao.queryDoctorAllInfo(roleName));
    }
    /**
     * @Author jianghy
     * @Description 后台端平台数据-医生数
     * @date
     * @return void
     */
    public void queryDoctorNum(){
        Map map = new LinkedHashMap();
        String roleName = getPara("roleName");//接收值为：医生
        String startTime = getPara("startTime");
        String endTime = getPara("endTime");
        //格式转换
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //当前时间
        Date n = new Date();
        //当前时间的近一个月时间
        Calendar c = Calendar.getInstance();
        c.setTime(n);
        c.add(Calendar.MONTH, -1);
        Date m = c.getTime();
        //初始化时间为空
        if(startTime==null||"".equals(startTime))
            //现在的时间 格式yyyy-MM-dd
            startTime = format.format(m);
        if(endTime==null||"".equals(endTime))
            //近一个月的时间 格式yyyy-MM-dd
            endTime = format.format(n);
        //计算时间差
        int daysBetween = 0;
        Date d1= new Date();
        Date d2= new Date();
        try{
            d1=format.parse(startTime);
            d2=format.parse(endTime);
            //两个时间相差的天数
            daysBetween = new Long((d2.getTime()-d1.getTime())/(60*60*24*1000)).intValue()+1;
        }catch (Exception e){
            e.printStackTrace();
        }
        int countNum = 0;//某时间断新增医生总数
        String[] createTime = new String[daysBetween];
        String[] counts = new String[daysBetween];
        if(!"".equals(roleName)||roleName!=null){
            for(int i=0;i<daysBetween;i++) {
                Date date = new Date();
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(d1);
                calendar.add(Calendar.DATE, i);
                date = calendar.getTime();
                String time = format.format(date);
                int count = TmDoctorUser.dao.queryDoctorNum(roleName,time);
                countNum+=count;
                counts[i] = String.valueOf(count);
                createTime[i] = time;
            }
            map.put("createTime",createTime);
            map.put("counts",counts);
            map.put("countNum",countNum);
            renderJsonRet(map);
        }else{
            renderJsonError(50002,"查询");
        }

    }

    //***医生端关于科室的接口*******************************************************************************

    /** **
     * @Author: chen
     * @Description:医生端科室添加成员时的列表查询
     * @Date: 15:26 2018/12/4
     * @param: [
     *              hosId       ---医院id
     *              depId       ---科室id
     *          ]
     * @return: void
     */
    public void findDempatmentMembersByHosId(){
        try{
            String hosId = getPara("hosId");
            String depId = getPara("depId");
            List<TmDoctorUser> data = TmDoctorUser.dao.findDempatmentMembersByHosId(hosId,depId);
            renderJsonRet(data);
        }catch (Exception e){
            e.printStackTrace();
            renderJsonError(50002,"医生端科室添加列表查询");
        }
    }

    /** GET
     * @Author: chen
     * @Description:医生端群组添加医生列表查询
     * @Date: 16:01 2018/12/4
     * @param: [
     *              departmentId   ---医院id
     *              groupId ---群组id
     *          ]
     * @return: void
     */
    public void findGroupMembersByHostId(){
        try {
            String departmentId = getPara("departmentId");
            String groupId = getPara("groupId");
            List<TmDoctorUser> data = TmDoctorUser.dao.findGroupMembersByHostId(departmentId,groupId);
            renderJsonRet(data);
        }catch (Exception e){
            e.printStackTrace();
            renderJsonError(50002,"群组添加医生列表查询");
        }
    }

}
